package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Banner;
import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.query.BannerQuery;
import cn.wolfcode.wolf2w.repository.BannerRepository;
import cn.wolfcode.wolf2w.service.IBannerService;
import cn.wolfcode.wolf2w.service.IStrategyService;
import cn.wolfcode.wolf2w.service.ITravelService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 广告推荐服务接口实现
 */
@Service
//@Transactional  现在写不能事务, 需要讲完复制集才能使用事务
public class BannerServiceImpl implements IBannerService {

    @Autowired
    private BannerRepository repsitory;

    @Autowired
    private MongoTemplate template;

    @Autowired
    private IStrategyService strategyService;

    @Autowired
    private ITravelService travelService;

    @Override
    public void save(Banner banner) {
        banner.setId(null);
        repsitory.save(banner);
    }

    @Override
    public void update(Banner banner) {
        repsitory.save(banner);
    }

    @Override
    public void delete(String id) {
        repsitory.deleteById(id);
    }

    @Override
    public Banner get(String id) {
        return repsitory.findById(id).orElse(null);
    }

    @Override
    public List<Banner> list() {
        return repsitory.findAll();
    }

    @Override
    public Page<Banner> query(BannerQuery qo) {
        Query query = new Query();
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, query, qo, Banner.class, pageable);
    }

    @Override
    public void saveOrUpdate(Banner banner) {
        if (StringUtils.hasLength(banner.getId())) {
            //update
            this.update(banner);
        } else {
            //save
            this.save(banner);
        }
    }

    @Override
    public Map<String, List> getAllType() {
        HashMap<String, List> map = new HashMap<>();
        map.put("sts", strategyService.list());
        map.put("ts", travelService.list());
        return map;
    }

    @Override
    public List<Banner> findBystateAndtype(int type) {
        Pageable pageable = PageRequest.of(0, 5, Sort.Direction.DESC, "sequence");
        List<Banner> banners = repsitory.findByStateAndType(Banner.STATE_NORMAL, type, pageable);
        return banners;
    }
}
